<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="唯一识别码" prop="uuid">
        <el-input
          v-model="queryParams.uuid"
          placeholder="请输入唯一识别码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户编号" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MEMBER_PARTNER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="createPartnerCode()"
          v-hasPermi="['member:partner-user:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 生成入驻码
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['member:partner-user:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
<!--  入住码展示-->
  <ContentWrap>
    <el-card>
      <div class="flex justify-between items-center">
        <div class="flex flex-row justify-between items-center">当前入驻码：<text class="text-[30px]">{{partnerCodeInfo.partnerCode}}</text></div>
        <div>
          <el-countdown title="更新倒计时" :value="partnerCodeInfo.expirationTime" />
        </div>
      </div>
    </el-card>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="唯一识别码" align="center" prop="uuid" />
      <el-table-column label="入驻码" align="center" prop="partnerCode" />
      <el-table-column label="用户编号" align="center" prop="userId" >
        <template #default="scope">{{scope.row.userName}}</template>
      </el-table-column>
      <el-table-column label="利润比例" align="center" prop="profitRatio" />
      <el-table-column label="总收入" align="center" prop="totalPrice" />
      <el-table-column label="可提现余额" align="center" prop="amount" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MEMBER_PARTNER_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="负责地区" align="center" prop="areaIds">
        <template #default="scope">
          <p v-for="(area,index) in scope.row.areaNames" :key="index">{{area}}</p>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['member:partner-user:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['member:partner-user:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PartnerUserForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { PartnerUserApi, PartnerUserVO } from '@/api/member/partneruser'
import PartnerUserForm from './PartnerUserForm.vue'
import {PartnerCodeApi, PartnerCodeVO } from "@/api/member/partnercode";

/** 城市合伙人 列表 */
defineOptions({ name: 'PartnerUser' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<PartnerUserVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  uuid: undefined,
  partnerCode: undefined,
  userId: undefined,
  profitRatio: undefined,
  totalPrice: undefined,
  amount: undefined,
  status: undefined,
  areaIds: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const partnerCodeInfo = ref({
  id:0,
  partnerCode:'',
  expirationTime:0,
})
// const timeInterval = ref()
const fetchInterval = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PartnerUserApi.getPartnerUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

// 生成入驻吗
const createPartnerCode = async() => {
  try {
    // 生成的二次确认
    await message.confirm("每次创建会生成10个新的入驻码，用户填入后将完成绑定哦！")
    // 发起删除
    await PartnerUserApi.createPartnerUser({partnerCode:10})
    message.success(t('common.success'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PartnerUserApi.deletePartnerUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PartnerUserApi.exportPartnerUser(queryParams)
    download.excel(data, '城市合伙人.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
// const updateExpirationTime = () => {

// }

const fetchLatestPartnerCode = async () => {
  try {
    partnerCodeInfo.value = await PartnerCodeApi.getPartnerCode()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
  fetchLatestPartnerCode()
  // 每1秒更新到期时间
  // timeInterval.value = setInterval(updateExpirationTime, 1000)
  // 每5秒请求最新的 partnerCode 记录
  fetchInterval.value = setInterval(fetchLatestPartnerCode, 5000)
})
onUnmounted(() => {
  // clearInterval(timeInterval.value);
  clearInterval(fetchInterval.value);
});
</script>
